#include "misc.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_tim.h"

static void (*tick)(void);

void TIM2_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM2, TIM_IT_Update))
    {
        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
        if (tick) tick();
    }
}

void timer_init(void)
{
    NVIC_InitTypeDef NVIC_InitStruct =
    {
        .NVIC_IRQChannel = TIM2_IRQn,
        .NVIC_IRQChannelPreemptionPriority = 0,
        .NVIC_IRQChannelSubPriority = 1,
        .NVIC_IRQChannelCmd = ENABLE
    };
    NVIC_Init(&NVIC_InitStruct);

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct =
    {
        .TIM_Prescaler = 2000 - 1,
        .TIM_CounterMode = TIM_CounterMode_Down,
        .TIM_Period = 36000 - 1,
        .TIM_ClockDivision = TIM_CKD_DIV1
    };
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
    TIM_Cmd(TIM2, ENABLE);
}

void timer_on_tick(void (*on_tick)(void))
{
    tick = on_tick;
}
